package com.example.whatrubbish.controller;

import com.alibaba.fastjson.JSON;
import com.example.whatrubbish.model.Admin;
import com.example.whatrubbish.service.AdminService;
import com.example.whatrubbish.service.LoginRecordService;
import com.example.whatrubbish.utils.Constants;
import com.example.whatrubbish.utils.GetIpAddrUtil;
import com.example.whatrubbish.utils.HttpRequest;
import com.example.whatrubbish.utils.JsonResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Log4j2
@CrossOrigin
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    AdminService adminService;
    @Autowired
    LoginRecordService loginRecordService;

    @ResponseBody
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public JsonResult adminLogin(HttpServletRequest request, Admin admin){
        JsonResult jsonResult;
        try{
            Admin admin1 = adminService.selectByNameAndPass(admin);
            if(admin1 == null)
                return new JsonResult(Constants.STATUS_NOT_FOUND, "fail");
            String result = HttpRequest.sendGet("https://apis.map.qq.com/ws/location/v1/ip", "ip=" + GetIpAddrUtil.getIpAddr(request) + "&key=ZD2BZ-UH7WP-TQ4DI-LYECP-ZNYDS-NGBLD");
            log.info(result);
            Map map = (Map) JSON.parse(result);
            if ("0".equals(map.get("status").toString())) {
                Map ipAddr = (Map) JSON.parse(map.get("result").toString());
                loginRecordService.insertSelective(ipAddr, admin1);
            }
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "success", admin1.getAdminId());
        }catch (Exception e){
            jsonResult = new JsonResult(Constants.STATUS_FAIL, "error");
        }
        return jsonResult;
    }
}
